package db

import (
	"com.jiaguyu/model"
	"database/sql"
	"fmt"

	"com.jiaguyu/until"
	"github.com/jmoiron/sqlx"

	"com.jiaguyu/logger"
)

var (
	PasswordSalt = "5R%LCY8wTd!p4YOd" //破解此密码需要一万年
)

func Register(user *model.UserInfo) (err error) {
	var count int64
	sqlstr := `select count(user_id) from user where username=?`
	err = DB.Get(&count, sqlstr, user.UserName)
	if err != nil && err != sql.ErrNoRows {
		return
	}

	//说明已经存在这个用户名 返回借口有存在
	fmt.Println(count, "count")
	if count > 0 {
		err = ErrUserExists
		return
	}

	//密码需要加密 md5 密码 加盐 不知道字符串
	password := user.Password + PasswordSalt

	//做个md5
	dbPassword := until.Md5([]byte(password))
	sqlStr := `insert into user(username,password,email,user_id,nickname,sex) values(?,?,?,?,?,?)`
	_, err = DB.Exec(sqlStr, user.UserName, dbPassword, user.Email, user.UserId, user.NickName, user.Sex)
	return
}

func Login(user *model.UserInfo) (err error) {
	originPassword := user.Password //保存原先用户传过来的
	sqlstr := `select username,password,user_id from user where username=?`
	err = DB.Get(user, sqlstr, user.UserName)
	//if err !=nil && err !=sql.ErrNoRows{
	//	return
	//}
	//说明不存用户
	if err == sql.ErrNoRows {
		err = ErrUserNotExists
		return
	}

	//密码需要加密 md5 密码 加盐 不知道字符串

	password := originPassword + PasswordSalt

	//做个md5
	userPassword := until.Md5([]byte(password))

	if userPassword != user.Password {
		err = ErrUserpassword
		return
	}
	//成功 直接 返回
	return
}

//type UserInfo struct {
//	UserId     int64     `json:"user_id" db:"user_id"`
//	NickName   string    `json:"nickname" db:"nickname"'`
//	Sex        int       `json:"sex" db:"sex"`
//	UserName   string    `json:"user" db:"username"`
//	Email      string    `json:"email" db:"email"`
//	Password   string    `json:"password" db:"password"'`
//	CreateTime time.Time `db:"create_time"`
func GetUserInfoList(userIdList []int64) (userInfoList []*model.UserInfo, err error) {
	if len(userIdList) == 0 {
		return
	}
	sqlStr := `select 
                     user_id,username,nickname ,sex,email 
                from user where user_id  in(?)`
	var userTempArr []interface{}
	for _, userId := range userIdList {
		userTempArr = append(userTempArr, userId)
	}
	//转换数组
	query, args, err := sqlx.In(sqlStr, userTempArr)
	if err != nil {
		logger.Error("SQLX 出问题%v、n", err)
		return
	}
	err = DB.Select(&userInfoList, query, args...)
	if err != nil {
		logger.Error("问题列表查询失败err:%v\n", err)
		return
	}
	return
}
